package com.vanzo.nfc;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;

import com.vanzo.encryption.Encryption;
import com.vanzo.encryption.R;

public class ReceiverActivity extends AppCompatActivity {

    public static final String TAG = "ReceiverActivity";

    NFCManager nfcMger;
    private TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        nfcMger = new NFCManager(this);
        this.text = (TextView) findViewById(R.id.sample_text);
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            nfcMger.verifyNFC();
            nfcMger.stopBind();
        } catch (NFCManager.NFCNotSupported nfcnsup) {
            Toast.makeText(this, R.string.nfc_unsupport, Toast.LENGTH_SHORT).show();
        } catch (NFCManager.NFCNotEnabled nfcnEn) {
//            Toast.makeText(this, "nfc not enable", Toast.LENGTH_SHORT).show();
            AlertDialog.Builder b = new AlertDialog.Builder(this);
            b.setTitle(R.string.nfc_unenable);
            b.setMessage(R.string.open_nfc);
            b.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_NFC_SETTINGS);
                    startActivity(intent);
                }
            });
            b.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            b.show();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Encryption.NFC binary = nfcMger.readBinaryFromTag(intent);
        text.setText(binary != null ? "接收到的数据：" + binary.toString() : "解析失败");
    }
}
